﻿/*
 * Torrent definition
 * 
 * Author: snowdreamist
 * Date: 2011/11/18
 * 
 */

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using BitTorrentSharp.BEncoding;

namespace BitTorrentSharp.Torrent
{
    public class TorrentFile
    {
        #region static

        public static TorrentFile CreateFromFile(string filepath)
        {
            if (string.IsNullOrWhiteSpace(filepath))
                throw new ArgumentException("Invalid filepath");
            
            TorrentFile torrent = null;

            using (var stream = new FileStream(filepath, FileMode.Open))
            {
                // torrent
                torrent = new TorrentFile(MetaInfo.CreateFromStream(stream));
                // info hash
                torrent.InfoHash = GetInfoHash(torrent.MetaInfo.OrginalInformation);
            }

            return torrent;
        }

        private static byte[] GetInfoHash(BDictionary dict)
        {
            byte[] content = null;

            using (var memStream = new MemoryStream())
            {
                dict[MetaInfo.InfoKey].Serialize(memStream);
                content = memStream.ToArray();
            }
            // need cut
            SHA1Managed shaMgr = new SHA1Managed();
            return shaMgr.ComputeHash(content);
        }

        #endregion

        public TorrentFile(MetaInfo metaInfo)
        {
            if (metaInfo == null)
                throw new ArgumentNullException("metaInfo");
            this.MetaInfo = metaInfo;
        }
        /// <summary>
        /// meta info
        /// </summary>
        public MetaInfo MetaInfo { get; private set; }
        /// <summary>
        /// info hash
        /// </summary>
        public byte[] InfoHash { get; private set; }
    }
}
